﻿using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using SyncService.Abstractions.Services;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;

namespace SyncService.Core.Services
{
    [Export(typeof(ISyncService))]
    [ExportMetadata(YdConstants.ID, "UpdateStaffGroup")]
    public class UpdateStaffGroupService : SyncServiceBase
    {
        protected override string NotifyGroupName => "";
        public UpdateStaffGroupService() : base(YdConstants.YIDEA, "mysqlcache", "")
        {

        }
        public override void Execute(dynamic? state)
        {
            try
            {
                var districtField = ExtendFields.First(e => e.Name == "区域" && e.ObjectType == 58);
                //拉取所有tag
                //拉取所有员工
                //循环更新员工tag
                List<EmployeeTags> empTags = YideaClient.GetEmployeeTags(null).ToList();
                List<Employee> employees=YideaClient.GetEmployees(null).ToList();
                foreach(Employee employee in employees)
                {
                    var empId = employee.Id ?? Guid.Empty;
                    if (!string.IsNullOrEmpty(employee.DataJson)) {
                        var dataJson = JsonNode.Parse(employee.DataJson).AsObject();
                        if (dataJson != null && dataJson[districtField.FieldId] != null)
                        {
                            var districtList = JsonNode.Parse(dataJson[districtField.FieldId].ToString()).AsArray();
                            var empTag = new List<string>();
                            foreach (var district in districtList)
                            {
                                var tag = empTags.Where(e => e.Name == district["label"].ToString()).FirstOrDefault();
                                if (tag != null)
                                {
                                    empTag.TryAdd(tag.Id.ToString());
                                }

                            }
                            if (empTag.Count > 0)
                            {
                               
                                YideaClient.UpdateEmployeeTags(new AddEmployeeTags() { EmployeeId = empId, EmployeeTagIds = empTag.ToArray() });
                            }

                        }
                        else {
                            YideaClient.UpdateEmployeeTags(new AddEmployeeTags() { EmployeeId = empId, EmployeeTagIds = new string[] { } });
                        }
                    }
                }
            }
            catch(Exception ex) {
                Logger.Error("更新员工组error:"+ex.ToString());
            }
        }

            }
}
